<?php

class RoleController extends Admincontroller
{
    public function init()
    {
        parent::init();
        $this->_role = new RoleModel();
        $this->_power = new PowerModel();
    }

    public function listAction()
    {
        $this->_view->assign("title", '角色管理');
        $this->_view->assign("activetitle", '角色管理');
        $this->_view->assign("parentmenu", '用户管理');
        $this->_view->assign("action", '角色管理');

        if ($this->getRequest()->isPost()) {
            $search = $this->getRequest()->getPost('search');
            $limit = $this->getRequest()->getPost('limit');
            $offset = $this->getRequest()->getPost('offset');

            $userdata = $this->_role->selectAll($offset, $limit, $search);
            $returnarray = array(
                        "total"=> $userdata['0'],
                        "rows" => isset($userdata['1'])?$userdata['1']:[]
                    );
            exit ( json_encode($returnarray) );
        }
        $this->_view->display('Role/list');
    }

    public function addAction()
    {
        $this->_view->assign("title", '新增角色');
        $this->_view->assign("activetitle", '角色管理');
        $this->_view->assign("parentmenu", '用户管理');
        $this->_view->assign("action", '新增角色');
        
        if ($this->getRequest()->isPost()) {
            //校验数据
            $validator = new Validata($this->getRequest()->getPost());
            $validator->field('name')->minLength(2)->maxLength(32);
            $validator->field('description')->minLength(2)->maxLength(128);
            
            if($validator->validate())
            {
                $info['name'] = $this->getRequest()->getPost('name');
                $info['description'] = $this->getRequest()->getPost('description');
                
                //插入数据
                $return = $this->_role->insert($info);
                if ($return) {
                    $returnarray = array('status' => '1', 'data' => '新增角色成功' );
                    exit ( json_encode($returnarray) );
                } else {
                    $returnarray = array('status' => '0', 'data' => '新增角色失败' );
                    exit ( json_encode($returnarray) );
                }
            }
            else
            {
                //校验不通过，输出校验数据的结果
                $returnarray = array('status' => '0', 'data' => $validator->getErrorAsString(true) );
                exit ( json_encode($returnarray) );
            }
        }
        
        $this->_view->display('Role/add');
    }

    public function editAction()
    {
        $this->_view->assign("title", '编辑角色');
        $this->_view->assign("activetitle", '角色管理');
        $this->_view->assign("parentmenu", '用户管理');
        $this->_view->assign("action", '编辑角色');

        if ($this->getRequest()->isPost()) {
            //校验数据
            $validator = new Validata($this->getRequest()->getPost());
            $validator->field('name')->minLength(2)->maxLength(32);
            $validator->field('description')->minLength(2)->maxLength(128);
            
            if($validator->validate())
            {
                $info['name'] = $this->getRequest()->getPost('name');
                $info['description'] = $this->getRequest()->getPost('description');
                $info['status'] = $this->getRequest()->getPost('status');
                $info['id'] = $this->getRequest()->getPost('id');
                
                //插入数据
                $return = $this->_role->update($info);
                if ($return) {
                    $returnarray = array('status' => '1', 'data' => '编辑权限成功' );
                    exit ( json_encode($returnarray) );
                } else {
                    $returnarray = array('status' => '0', 'data' => '编辑权限失败' );
                    exit ( json_encode($returnarray) );
                }
            }
            else
            {
                //校验不通过，输出校验数据的结果
                $returnarray = array('status' => '0', 'data' => $validator->getErrorAsString(true) );
                exit ( json_encode($returnarray) );
            }
        }
        
        // 获取指定id的角色信息
        $id = $this->getRequest()->get('id');
        $data = $this->_role->find($id);
        if($data){
            $this->_view->assign("data", $data);
            
            $this->_view->display('role/edit');
        }else{
            $this->_view->assign("msg", '指定要编辑的角色不存在');
            $this->_view->display('Public/error');
        }
    }
    
    public function setpowerAction()
    {
        $this->_view->assign("title", '设置权限');
        $this->_view->assign("activetitle", '角色管理');
        $this->_view->assign("parentmenu", '用户管理');
        $this->_view->assign("action", '设置权限');
        
        $id = $this->getRequest()->get('id');
        
        if ($this->getRequest()->isPost()) {
            //插入数据
            $access = explode(",", $this->getRequest()->getPost('powerid'));
            $return = $this->_role->updateaccess($id, $access);
            if ($return) {
                $returnarray = array('status' => '1', 'data' => '设置权限成功' );
                exit ( json_encode($returnarray) );
            } else {
                $returnarray = array('status' => '0', 'data' => '设置权限失败' );
                exit ( json_encode($returnarray) );
            }
        }
        
        // 获取指定id的角色信息
        $data = $this->_role->find($id);
        if($data){
            $this->_view->assign("data", $data);
            
            // 获取权限列表信息
            $result = $this->_power->getallpower();
            foreach ($result as $m){
                $newmenus[$m['id']]=$m;
            }
            
            // 获取角色已分配的权限
            $access = $this->_role->getaccess($id);
            
            // 生成权限树
            foreach ($result as $n => $t) {
                $result[$n]['checked'] = ($this->_is_checked($t, $access)) ? ' checked' : '';
                $result[$n]['level'] = $this->_get_level($t['id'], $newmenus);
                $result[$n]['parentid_node'] = ($t['parentid']) ? ' class="child-of-node-' . $t['parentid'] . '"' : '';
            }
            // debug($result);
            $tree = new Tree();
            $tree->icon = array('│ ', '├─ ', '└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $str = "<tr id='node-\$id' \$parentid_node>
                      <td style='padding-left:30px;'>
                        \$spacer <input type='checkbox' name='powerid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> &nbsp;&nbsp;&nbsp; \$title
                      </td>
                    </tr>";
            $tree->init($result);
            $power = $tree->get_tree(0, $str);
            $this->_view->assign("power", $power);
            
            $this->_view->display('role/setpower');
        }else{
            $this->_view->assign("msg", '指定要设置权限的角色不存在');
            $this->_view->display('Public/error');
        }
    }
    
    private function _is_checked($power, $access) {
    	if($access){
	    	if (in_array($power['id'], $access)) {
	    		return true;
	    	} else {
	    		return false;
	    	}
    	}else{
    		return false;
    	}
    	
    }
    
    private function _get_level($id, $array = array(), $i = 0) {
        if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
            return  $i;
        }else{
            $i++;
            return $this->_get_level($array[$id]['parentid'],$array,$i);
        }
    }
}
